package com.wx.sftp.impl;

import com.wx.sftp.Jcraft;
import com.wx.sftp.JcraftPool;
import com.wx.sftp.config.SaasFtpConf;
import com.jcraft.jsch.ChannelSftp;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;

import java.util.function.Function;

/**
 * @author 刘畅
 * @date 2018-12-11 23:19
 */
@Slf4j
@SuppressWarnings("unused")
public class PooledSaasFtp extends BaseSaasFtp {

  private JcraftPool pool;
  private SaasFtpConf.PoolConfig poolConf;

  public PooledSaasFtp(SaasFtpConf conf) {
    super(conf);
    poolConf = conf.getPool();
    pool = new JcraftPool(conf);
  }

  @Override
  public void close() {
    pool.close();
  }

  @Nullable
  @Override
  <R> R apply(Function<ChannelSftp, R> function) {
    Jcraft jcraft = null;
    try {
      jcraft = pool.borrowObject(poolConf.getMaxWaitMillis());
      ChannelSftp sftp = jcraft.getSftp();
      return function.apply(sftp);
    } catch (Exception e) {
      log.warn("获取sftp连接失败:", e);
      return null;
    } finally {
      if (jcraft != null) {
        pool.returnObject(jcraft);
      }
    }
  }
}
